"use strict";

var router = require("router"),
    TokenService = require("router").TokenService,
    mongo = require('./core/mongoservice'),
    ObjectId = require('mongodb').ObjectID,
    Q = require('q');

function ShopCategoryService() {
    console.log("ShopCategoryService constructor");
}
ShopCategoryService.prototype = Object.create(TokenService.prototype);
ShopCategoryService.prototype.constructor = ShopCategoryService;

ShopCategoryService.prototype.insert = function (request, response, promise) {
    return promise.then(function (self) {
        //self.identify(request, response);
        return self.mongoSave(request.body).then(function (data) {
            return response.send({ request: request, content: data });
        });
    });
};

ShopCategoryService.prototype.getGroupList = function (request, response, promise) {
    return promise.then(function (self) {

        var skip = parseInt(request.query.skip);
        var limit = parseInt(request.query.limit);

        return self.mongoGetGroupList({ skip: skip, limit: limit}).then(function (data) {
            return response.send({ request: request, content: data });
        });
    });
};

/*-------------------------------------------------------*/
/*mongo daf*/

ShopCategoryService.prototype.mongoInsert = function (group) {
    return Q.fcall(function () {
        if (!group) throw new Error("group is not defined.");
        if (group._id) throw new Error("group already has id: " + group._id);
        var self = this;

        return mongo.insert('shops.categories', group).then(function (groupes) {
            return groupes[0];
        }).then(function (group) {
            var promises = [];
            group.categories.forEach(function (category) {
                promises.push(require("./researchservice").mongoSave(category.name));
            });
            return Q.all(promises).then(function () {
                return group;
            });
            //TODO mettre à jour toutes les "shops"
        });
    });
};


ShopCategoryService.prototype.mongoSave = function (group) {
    return Q.fcall(function () {
        if (!group) throw new Error("group is not defined.");
        if (!group.name) throw new Error("name is not defined.");
        var self = this;

        var query = group.name;
        query = query.replace(new RegExp(" ", 'g'), '\\s');
        var regex = new RegExp("^" + query + "$", "ig");

        return mongo.findOne('shops.categories', { name: { $regex: regex} }).then(function (res) {
            if (res) return self.mongoUpdate(group);
            return self.mongoInsert(group);
        });
    });
};


ShopCategoryService.prototype.mongoGetGroupList = function (options) {

    options = options || {};

    var opts = {};
    options = options || {}
    if (options.limit) opts.limit = options.limit;
    if (options.skip) opts.skip = options.skip;
    opts.sort = {"name": 1};

    return mongo.find('shops.categories', { }, opts).then(function (cursor) {
        return Q.ninvoke(cursor, 'toArray');
    });
};

ShopCategoryService.prototype.mongoGetByGroup = function (query) {
    return Q.fcall(function () {
        if (!query) throw new Error("query is not defined.");

        query = query.replace(new RegExp(" ", 'g'), '\\s');
        var regex = new RegExp("^" + query + "$", "ig");

        return mongo.findOne('shops.categories', { name: { $regex: regex} });
    });
};


exports = module.exports = new ShopCategoryService();